package com.global.query;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.global.base.StringUtil;
import com.global.dao.jdbc.GenericJdbcDao;
import com.global.model.DataSourceX;
import com.global.model.DataSourceXColumn;
import com.global.vo.*;

public class ResultSetOutput implements Serializable {

	private final Log log = LogFactory.getLog(getClass());
	
	private static final long serialVersionUID = -2165155242749375251L;

	List<String> errorMessageList = new ArrayList<String>();
	
	private int columnCount;
	private DataSourceX dataSourceX;
	ResultSet rs;
	List<DBColumn> sqlMetaData = new ArrayList<DBColumn>();

    private List<RowValuesProperties> rowData = new ArrayList<RowValuesProperties>();
    	
	@Autowired
	GenericJdbcDao jdbcDao;
	
    public ResultSetOutput(DataSourceX dataSourceX, ResultSet rs) throws SQLException {
    	this.dataSourceX = dataSourceX;
    	this.rs = rs;
    	
    	sqlMetaData = jdbcDao.getSQLMetaData(rs);    	
    	columnCount = (rs.getMetaData()==null ? 0 : rs.getMetaData().getColumnCount());
    	
    	if(validateConfig()){
    		initData(rs);
    	}
    }

    /**
     * 获取行数据
     * @param rs
     * @return
     * @throws SQLException
     */
    private List<RowValuesProperties> initData(ResultSet rs) throws SQLException {
        
        while (rs.next()) {
        	RowValuesProperties rowValuesProperties = new RowValuesProperties(columnCount);
        	
        	for(DataSourceXColumn column : dataSourceX.getDataSourceXColumns()){
        		Object value = rs.getObject(column.getDisplayIndex());
        		CellValueProperties newValue = this.getNewValue(column.getAlias(), value);
        		
        		rowValuesProperties.add(newValue);
        	}            
        	
            rowData.add(rowValuesProperties);
        }
        
        return rowData;
    }

    /**
     * 获取结果集转后的记录集合
     * @return
     */
    public List<RowValuesProperties> getRowData(){
    	return rowData;
    }
    
    /**
     * 获取结果集对应的元数据
     * @return
     */
    public List<DBColumn> getMetaData(){
    	return sqlMetaData;
    }
    
    /**
     * 返回字段数
     * @return
     */
    public int getColumnCount() {
        return columnCount;
    }
    
    /**
     * 验证配置是否正确
     * @return
     */
    private boolean validateConfig(){
    	String errMsg = "";
    	
		List<DataSourceXColumn> dataSourceXColumns = dataSourceX.getDataSourceXColumns();
		if(dataSourceXColumns.isEmpty()){
			errMsg = "数据源【" + dataSourceX.getDescription() + "】没有配置字段，则无法显示数据，请联系系统管理员";
			errorMessageList.add(errMsg);
			
			return false;
		}else{
			if(columnCount!=dataSourceXColumns.size()){
				errMsg = "数据源【" + dataSourceX.getDescription() + "】配置的字段个数【" + dataSourceXColumns.size() + "】与配置的SQL查询出来的字段个数【" + columnCount + "】不一致，则无法显示数据，请联系系统管理员";
				errorMessageList.add(errMsg);
				log.error(errMsg);
				
				return false;
			}
		}

		//验证事先配置好的字段在SQL结果集中是否存在
		List<String> notExistColumns = new ArrayList<String>();
		for(DataSourceXColumn column : dataSourceX.getDataSourceXColumns()){
			boolean isExist = false;
			
			for(DBColumn dbColumn : sqlMetaData) {
				if(dbColumn.getAlias().equalsIgnoreCase(column.getAlias())){
					isExist = true;
					break;
				}
			}
		
			if(!isExist){
				notExistColumns.add(column.getAlias());
			}
		}
		if(!notExistColumns.isEmpty()){
			errMsg = "数据源【" + dataSourceX.getDescription() + "】配置的字段【" + StringUtil.getString(notExistColumns, ",") + "】在执行查询时没有找到，则无法显示数据，请联系系统管理员";
			errorMessageList.add(errMsg);
			log.error(errMsg);
			
			return false;
		}
		
		//验证从SQL结果集中获取到的字段在事先配置好的字段中是否存在
		notExistColumns.clear();
		for(DBColumn dbColumn : sqlMetaData) {
			boolean isExist = false;
			
			for(DataSourceXColumn column : dataSourceX.getDataSourceXColumns()){
				if(dbColumn.getAlias().equalsIgnoreCase(column.getAlias())){
					isExist = true;
					break;
				}
			}
			
			if(!isExist){
				notExistColumns.add(dbColumn.getAlias());
			}
		}
		if(!notExistColumns.isEmpty()){
			errMsg = "执行数据源【" + dataSourceX.getDescription() + "】时获取到的字段【" + StringUtil.getString(notExistColumns, ",") + "】在配置的字段清单中不存在，则无法显示数据，请联系系统管理员";
			errorMessageList.add(errMsg);
			log.error(errMsg);
			
			return false;
		}
		
		return true;
    }
    
    /**
     * 获取栏位的key-value
     * @param key
     * @param oldValue
     * @return
     */
    private CellValueProperties getNewValue(String key, Object value){    	
    	
    	String valueStr = StringUtil.getValueStr(value);
    	String message = StringUtil.getErrorMessage();
    	
    	return new CellValueProperties(key, valueStr, message);
    }
}